//
//  DetailViewController.m
//  Zyachting
//
//  Created by NGUYEN THE HUNG on 10/18/12.
//
//

#import "DetailViewController.h"
#import "ImageViewerController.h"
#import "JSON.h"
#import "DetailCell.h"
#import "RecommendViewController.h"
#import "UIImageView+WebCache.h"
#import  <Twitter/Twitter.h>
#import <Accounts/Accounts.h>
@interface DetailViewController ()

@end

@implementation DetailViewController
@synthesize infoDict,imageViewerController,tableView,imageList;
@synthesize scrollView;
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    HUD = [[MBProgressHUD alloc] initWithView:self.view];
    [HUD setLabelText:@"Loading"];
    [self.view addSubview:HUD];
    self.navigationItem.title = @"Details";
    [self getImageList];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(facebookDidLogin) name:@"" object:nil];

}
-(void)dealloc{
    [HUD release];
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    [super dealloc];
}
-(void)facebookDidLogin{
    NSString *thumbURL = [self.imageList objectAtIndex:0][@"imgpath"];
    NSString *imageLink = [NSString stringWithFormat:@"http://www.z-yachting.com/en/search-on-map?view=property&id=%d",[self.infoDict[@"id"] integerValue]];
    NSMutableDictionary* dialogParams = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                         @"425726260821083", @"app_id",
                                         imageLink, @"link",
                                         thumbURL, @"picture",
                                         @"Name here", @"name",
                                         nil];
    
    [[self appDelegate].facebook dialog:@"feed"
                              andParams:dialogParams
                            andDelegate:self];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
#pragma mark -
#pragma mark TableView DataSource Method
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
//    switch (section) {
//        case 0:
//            return 7;
//            break;
//        case 1:
//            return 5;
//            break;
//        case 2:
//            return 4;
//            break;
//        default:
//            break;
//    }
    return 4;
}

// Row display. Implementers should *always* try to reuse cells by setting each cell's reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
// Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)

- (UITableViewCell *)tableView:(UITableView *)tableView1 cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *DetailCellIdentifier = @"DetailCellIdentifier";
    DetailCell *cell = (DetailCell *)[tableView
                                              dequeueReusableCellWithIdentifier: DetailCellIdentifier];
    if (cell == nil) {
        NSArray *nib = [[NSBundle mainBundle] loadNibNamed:@"DetailCell"
                                                     owner:self options:nil];
        for (id oneObject in nib)
            if ([oneObject isKindOfClass:[DetailCell class]])
                cell = (DetailCell *)oneObject;
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    switch (indexPath.row) {
//        case 0:
//            cell.lblTitle.text = @"Reference ID:";
//            cell.ivIcon.hidden = YES;
//            cell.lblValue.text = [self.infoDict objectForKey:@"mls_id"];
//            break;
        case 3:
            cell.lblTitle.text = @"Price:";
            cell.ivIcon.hidden = YES;
            cell.lblValue.text = [NSString stringWithFormat:@"%d €",[[self.infoDict objectForKey:@"price"] integerValue]];
            break;
//        case 2:
//            cell.lblTitle.text = @"City:";
//            cell.ivIcon.hidden = YES;
//            cell.lblValue.text = [self.infoDict objectForKey:@"city"];
//            break;
//        case 3:
//            cell.lblTitle.text = @"Land:";
//            cell.ivIcon.hidden = YES;
//            cell.lblValue.text = [[self.infoDict objectForKey:@"sqft"] integerValue] == 0 ?@"--":self.infoDict[@"sqft"];
//            break;
        case 2:
            cell.lblTitle.text = @"Constructed are:";
            cell.ivIcon.hidden = YES;//constructed
            cell.lblValue.text = [[self.infoDict objectForKey:@"constructed"] integerValue] == 0 ?@"--":self.infoDict[@"constructed"];
            break;
        case 1:
            cell.lblTitle.text = @"Bathrooms:";
            cell.ivIcon.hidden = YES;
            cell.lblValue.text = [NSString stringWithFormat:@"%d",[[self.infoDict objectForKey:@"baths"] integerValue]];
            break;
        case 0:
            cell.lblTitle.text = @"Bedrooms:";
            cell.ivIcon.hidden = YES;
            cell.lblValue.text = [NSString stringWithFormat:@"%d",[[self.infoDict objectForKey:@"beds"] integerValue]];
            break;

        default:
            break;
    }
    return cell;
}

#pragma mark -
#pragma mark TableView Delegate Method
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 44;
}

#pragma mark -Helper
-(AppDelegate*)appDelegate
{
    return (AppDelegate*)([UIApplication sharedApplication].delegate);
}
-(void)setupView
{
    UIScrollView* scroller = [[UIScrollView alloc] initWithFrame:self.view.frame];
    [scroller setContentSize:CGSizeMake(320, 700)];
    [scroller setDelegate:self];
    [scroller setBackgroundColor:[UIColor clearColor]];
    [self.view addSubview:scroller];
    
    UILabel* lblTitle = [[UILabel alloc] initWithFrame:CGRectMake(10, 10, 300, 40)];
    [lblTitle setNumberOfLines:2];
    [lblTitle setFont:[UIFont boldSystemFontOfSize:17]];
    [lblTitle setTextAlignment:NSTextAlignmentCenter];
    [scroller addSubview:lblTitle];
    lblTitle.text = [NSString stringWithFormat:@"%@ %@",self.infoDict[@"mls_id"],self.infoDict[@"city"]];
    [lblTitle setBackgroundColor:[UIColor clearColor]];
    [lblTitle release];
    //ImageViewer
    self.imageViewerController = [[[ImageViewerController alloc] initWithNibName:@"ImageViewerController" bundle:nil] autorelease];
    self.imageViewerController.imageList = self.imageList;
    self.imageViewerController.isLocal = NO;
    [self.imageViewerController.view setFrame:CGRectMake(0, 60, 320, 250)];
    [scroller addSubview:self.imageViewerController.view];
    
    //TableView for displaying property, change height if needed
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 320, 320, 320) style:UITableViewStyleGrouped];
    [self.tableView setDelegate:self];
    [self.tableView setDataSource:self];
    [self.tableView setScrollEnabled:NO];
    [self.tableView setUserInteractionEnabled:NO];
    [self.tableView setBackgroundColor:[UIColor clearColor]];
    [self.tableView setBackgroundView:nil];
    [scroller addSubview:self.tableView];
    
    UIButton* inquireBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [inquireBtn setImage:[UIImage imageNamed:@"InquiryNow.png"] forState:UIControlStateNormal];
    [inquireBtn setFrame:CGRectMake(15, 530, 290, 45)];
    [inquireBtn addTarget:self action:@selector(inquireBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    [inquireBtn setTag:0];
    [scroller addSubview:inquireBtn];

    UIButton* RecommendBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [RecommendBtn setImage:[UIImage imageNamed:@"Recommend.png"] forState:UIControlStateNormal];
    [RecommendBtn setFrame:CGRectMake(15, 585, 290, 45)];
    [RecommendBtn addTarget:self action:@selector(inquireBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    [RecommendBtn setTag:1];
    [scroller addSubview:RecommendBtn];
    
    UIButton* shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [shareBtn setImage:[UIImage imageNamed:@"ShareBtn.png"] forState:UIControlStateNormal];
    [shareBtn setFrame:CGRectMake(15, 640, 290, 45)];
    [scroller addSubview:shareBtn];
    [shareBtn addTarget:self action:@selector(shareBtnTapped:) forControlEvents:UIControlEventTouchUpInside];
    self.scrollView = [scroller autorelease];
}
-(IBAction)shareBtnTapped:(id)sender
{
    UIActionSheet* actionSheet = [[UIActionSheet alloc] initWithTitle:@"Share" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Facebook",@"Twitter",@"Email", nil];
    [actionSheet setDelegate:self];
    [actionSheet showFromTabBar:self.tabBarController.tabBar];
    [actionSheet release];
}
-(IBAction)inquireBtnTapped:(id)sender
{
    RecommendViewController* inquireView = [[RecommendViewController alloc] initWithNibName:@"RecommendViewController" bundle:nil];
    [inquireView setIsInquired:[sender tag] == 0];
    [inquireView setInfoDict:self.infoDict];
    [self.navigationController pushViewController:inquireView animated:YES];
    [inquireView release];
}
-(void)getImageList
{
    //http://www.z-yachting.com/ws/getPicture.php?id=1
    [HUD show:YES];
    NSInteger aID = [[self.infoDict objectForKey:@"id"] integerValue];
    ASIHTTPRequest* request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://www.z-yachting.com/ws/getPicture.php?id=%d",aID]]];
    [request setDelegate:self];
    [request startAsynchronous];
    
}

#pragma mark - ActionSheet Delegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
            NSLog(@"FB");
        {
            if ([[self appDelegate].facebook isSessionValid]) {
                NSString *thumbURL = [self.imageList objectAtIndex:0][@"imgpath"];
                NSString *imageLink = [NSString stringWithFormat:@"http://www.z-yachting.com/en/search-on-map?view=property&id=%d",[self.infoDict[@"id"] integerValue]];
                NSMutableDictionary* dialogParams = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                                     @"425726260821083", @"app_id",
                                                     imageLink, @"link",
                                                     thumbURL, @"picture",
                                                     @"Name here", @"name",
                                                     nil];
                
                [[self appDelegate].facebook dialog:@"feed"
                                          andParams:dialogParams 
                                        andDelegate:self];
            }else{
                //Section expired, need to reauthenticated.
                [[self  appDelegate].facebook  authorize:[self appDelegate].userPermissions];
                
            }
        }
            break;
        case 1:
            NSLog(@"TW");
        {
//            [[self appDelegate] tweetWithMedia:[UIImage imageNamed:[self.imageList objectAtIndex:0][@"imgpath"]] andMessage:@"Your message here"];
            
            TWTweetComposeViewController *twitter = [[TWTweetComposeViewController alloc] init];

            [twitter setInitialText:@"This is the message that will be tweeted!"];
//             [twitter addImage:[UIImage imageNamed:@"image.png"]];
            UIImageView* iv = [[UIImageView alloc] init];
            [iv setImageWithURL:[NSURL URLWithString:[self.imageList objectAtIndex:0][@"imgpath"]]];
            if (iv.image !=nil) {
                [twitter addImage:iv.image];
            }
            [iv release];
            [self presentViewController:twitter animated:YES completion:nil];
                                
            twitter.completionHandler = ^(TWTweetComposeViewControllerResult res) {
                                    if(res == TWTweetComposeViewControllerResultDone) {
                                        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Success" message:@"The Tweet was posted successfully." delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles: nil];
            [alert show];
        }
        if(res == TWTweetComposeViewControllerResultCancelled) {
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Cancelled" message:@"You Cancelled posting the Tweet." delegate:self cancelButtonTitle:@"Dismiss" otherButtonTitles: nil];
            [alert show];
            }
                [self dismissViewControllerAnimated:YES completion:NULL];
            };
                                                                                        
        }
            break;
        case 2:
            NSLog(@"Email");
        {
            MFMailComposeViewController* mailComposer = [[MFMailComposeViewController alloc] init];
            [mailComposer setMailComposeDelegate:self];
            [mailComposer setMessageBody:[NSString stringWithFormat:@"http://www.z-yachting.com/en/search-on-map?view=property&id=%d",[self.infoDict[@"id"] integerValue]] isHTML:NO];
            [[self appDelegate].tabBarController presentViewController:mailComposer animated:YES completion:NULL];
            [mailComposer release];
        }
            break;
        default:
            break;
    }
}

#pragma mark - MailComposerDelegate
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error
{
    [[self appDelegate].tabBarController dismissViewControllerAnimated:YES completion:NULL];
    
}
#pragma mark - ASIHTTPRequest Delegate
- (void)requestFinished:(ASIHTTPRequest *)request
{
    [HUD hide:YES];
    self.imageList = [request.responseString JSONValue];
    [self setupView];
}
- (void)requestFailed:(ASIHTTPRequest *)request
{
    [HUD hide:YES];
    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Warning" message:@"Connection Fail. Please try again" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
    [alert show];
    [alert release];
}

#pragma mark FBRequest Delegate
- (void)request:(FBRequest *)request didLoad:(id)result {
    //For Initiate Profile
    //Fetch Facebook Id and name

}
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error {
    //indicator.hidden = YES;
    [HUD hide:YES];
    NSLog(@"%@",[error localizedDescription]);
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Message" message:[error localizedDescription] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
    [alert release];
}
- (void)dialogDidComplete:(FBDialog *)dialog {
    NSLog(@"Dialog did complete");
}


//=============================================================================================================================

@end
